//
//  UIViewController+Category.m
//  ChengHuiTong
//
//  Created by CHT-Technology on 2017/1/12.
//  Copyright © 2017年 张文权. All rights reserved.
//

#import "UIViewController+Category.h"
#import <objc/runtime.h>
#import "CALayer+Anim.h"

const void *WarnView = &WarnView;
const void *WarnViewClickBlock = &WarnViewClickBlock;
const void *CountDownBoxCompleteBlock = &CountDownBoxCompleteBlock;
const void *CountDownBoxReadBtn = &CountDownBoxReadBtn;

@implementation UIViewController (Category)

/**
 去登录
 */
- (void)goToLoginVCWithCompleteBlock:(void(^)(NSString *token))completeBlock{
    
    YPLogonViewController * logonVC = [[YPLogonViewController alloc]init];
    
    logonVC.completBlock = ^(NSString *token){
        
        if(completeBlock)(completeBlock(token));
    };
    
    BaseNavigationController * nav = [[BaseNavigationController alloc]initWithRootViewController:logonVC];
    
    [self presentViewController:nav animated:YES completion:^{
        
    }];
    
}

/**
 开启定时器
 
 @param limit 总时间
 @param progressBlock 跳动回调
 @param completeBlock 结束回调
 */
- (void)openTimerWithLimit:(int)limit
             progressBlock:(void(^)(NSString *seconds))progressBlock
             completeBlock:(void(^)())completeBlock{
    
    [UIViewController openTimerWithLimit:limit
                           progressBlock:progressBlock
                           completeBlock:completeBlock];
}


/**
 开启定时器

 @param limit 总时间
 @param progressBlock 跳动回调
 @param completeBlock 结束回调
 */
+ (void)openTimerWithLimit:(int)limit
             progressBlock:(void(^)(NSString *seconds))progressBlock
             completeBlock:(void(^)())completeBlock{
    
    __block int timeout=limit;
    BOOL singular = limit > 10?NO:YES;
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0);
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                
                !completeBlock? :completeBlock();
            });
            
        }else{
            
            NSString *strTime = singular?[NSString stringWithFormat:@"%d", timeout]:[NSString stringWithFormat:@"%.2d", timeout];
            dispatch_async(dispatch_get_main_queue(), ^{
                
                !progressBlock? :progressBlock(strTime);
                
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
}


/**
 警告弹窗
 
 @param text 警告内容
 @param textAlignment 内容对齐方式
 @param btnTitle 按钮标题
 @param block 按钮点击回调
 */
-(void)showWarnViewWithText:(NSString *)text
              textAlignment:(NSTextAlignment)textAlignment
                buttonTitle:(NSString *)btnTitle
                      block:(void(^)())block{
    
    UIView *_warnView  = objc_getAssociatedObject(self, WarnView);
    
    if (!_warnView) {
        
        _warnView=[[UIView alloc] initWithFrame:self.view.bounds];
        _warnView.backgroundColor=[UIColor colorWithWhite:0.3 alpha:0.3];
        [self.view addSubview:_warnView];
        
        objc_setAssociatedObject(self, WarnView, _warnView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        objc_setAssociatedObject(self, WarnViewClickBlock, block, OBJC_ASSOCIATION_COPY_NONATOMIC);
        
        CGFloat contentW = SCREEN_WIDTH*2/3.0;
        UIFont *textFont = [UIFont systemFontOfSize:14];
        CGFloat margin = 15;
        CGSize size = [text sizeWithFont:textFont andMaxSize:CGSizeMake(contentW - margin*2, 350)];
        
        UIView*view=[[UIView alloc] initWithFrame:CGRectMake(0, 0, contentW, MAX((SCREEN_WIDTH*2/3.0)*0.75, size.height+80))];
        view.backgroundColor=[UIColor whiteColor];
        view.center=_warnView.center;
        view.top=SCREEN_HEIGHT/2.0-view.height/2.0-64;
        [_warnView addSubview:view];
        
        
        UILabel*label=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, view.width, 40)];
        label.backgroundColor=kColor_AppNavColor;
        label.font=[UIFont systemFontOfSize:16];
        label.textAlignment=1;
        label.textColor=[UIColor whiteColor];
        label.text=@"提示";
        [view addSubview:label];
        
        UILabel*contentLabel=[[UILabel alloc] initWithFrame:CGRectMake(margin, label.bottom, contentW - margin*2, view.height - 80)];
        contentLabel.font= textFont;
        contentLabel.textColor=UIColorFromString(@"#7C7C7C");
        contentLabel.text=text;
        contentLabel.textAlignment=textAlignment;
        contentLabel.numberOfLines=0;
        [view addSubview:contentLabel];
        
        UIButton*goButton=[UIButton buttonWithType:UIButtonTypeCustom];
        goButton.frame=CGRectMake(0, view.height - 40, view.width, 40);
        [goButton setBackgroundColor:kColor_AppNavColor];
        [goButton addTarget:self action:@selector(goButtonClick) forControlEvents:UIControlEventTouchUpInside];
        [goButton setTitleColor:[UIColor whiteColor] forState:0];
        [goButton setTitle:btnTitle forState:0];
        goButton.titleLabel.font=[UIFont boldSystemFontOfSize:16];
        [view addSubview:goButton];
    }

}

- (void)goButtonClick{
    
    UIView *_warnView  = objc_getAssociatedObject(self, WarnView);
    [_warnView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    [_warnView removeFromSuperview];
    _warnView = nil;
    
    void (^ clickBlock)() = objc_getAssociatedObject(self, WarnViewClickBlock);
    !clickBlock? :clickBlock();
    //这里一定移除绑定，否则有内存泄漏
    objc_removeAssociatedObjects(self);
}



/**
 倒计时弹框
 
 @param title 标题
 @param content 内容
 @param completeTitle 完成按钮标题
 @param cancleTitle 取消按钮标题
 @param timelimit 总时间
 @param completeBlock 完成回调
 */
- (void)showCountDownBoxWithTitle:(NSString *)title
                      contentText:(NSMutableAttributedString *)content
                    completeTitle:(NSString *)completeTitle
                      cancleTitle:(NSString *)cancleTitle
                        timeLimit:(int)timelimit
                    completeBlock:(void(^)())completeBlock{
    
    UIView *bgView = [[UIView alloc]initWithFrame:self.view.bounds];
    bgView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.6];
    bgView.tag = 7890;
    [self.view addSubview:bgView];
    
    
    UIView *contentView = [[UIView alloc]initWithFrame:CGRectMake(leftMargin*2, 0, SCREEN_WIDTH - leftMargin*4, 100)];
    contentView.backgroundColor = [UIColor whiteColor];
    [bgView addSubview:contentView];
    
    UILabel *titleLb = [UILabel creatWithFrame:CGRectMake(0, 0, contentView.width, 30)
                                          font:[UIFont boldSystemFontOfSize:14]
                                          text:title
                                     textColor:[UIColor darkGrayColor]
                                 textAlignment:0];
    titleLb.userInteractionEnabled = YES;
    [titleLb addLine];
    [contentView addSubview:titleLb];
    
    
    UIButton *closeBtn = [UIButton creatWithFrame:CGRectMake(titleLb.width - 40, 0, 40, titleLb.height)
                                            image:ImageNamed(@"close")
                                           action:@selector(countDownBoxDismiss)
                                           target:self];
    [titleLb addSubview:closeBtn];
    
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:8];
    [content addAttributes:@{NSParagraphStyleAttributeName:paragraphStyle,
                                      NSFontAttributeName:[UIFont systemFontOfSize:14],
                                      }
                              range:NSMakeRange(0, [content length])];
    
    UILabel *contentLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, titleLb.bottom + 5, contentView.width - 20, 30)];
    contentLabel.textColor = [UIColor darkGrayColor];
    contentLabel.numberOfLines = 0;
    contentLabel.attributedText = content;
    CGRect rect = [content boundingRectWithSize:CGSizeMake(contentLabel.width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin context:nil];
    contentLabel.height = rect.size.height;
    [contentView addSubview:contentLabel];
    
    
    UILabel *remindLabel = [UILabel creatWithFrame:CGRectMake(contentLabel.left, contentLabel.bottom, contentLabel.width, 60)
                                              font:[UIFont systemFontOfSize:13]
                                              text:@"温馨提示:确认发起转让后，一切设置均不可更改，请慎重!"
                                         textColor:kColor_redNumberColor
                                     textAlignment:0];
    remindLabel.numberOfLines = 0;
    [contentView addSubview:remindLabel];
    
    
    UILabel *timeLabel = [UILabel creatWithFrame:CGRectMake(contentLabel.left, remindLabel.bottom, contentLabel.width, 20)
                                            font:[UIFont systemFontOfSize:13]
                                            text:[NSString stringWithFormat:@"(%ds)后可进行操作",timelimit]
                                       textColor:kColor_redNumberColor
                                   textAlignment:1];
    [contentView addSubview:timeLabel];
    
    
    UIButton *readBtn = [UIButton creatWithFrame:CGRectMake((contentView.width - 180)/2.f, timeLabel.bottom, 180, 25)
                                            font:timeLabel.font
                                            text:@"我已阅读并同意上述内容"
                                       textColor:[UIColor darkGrayColor]
                                           image:ImageNamed(@"cht_nocheck")
                                          action:@selector(countDownBoxRead:)
                                          target:self];
    [readBtn setImage:ImageNamed(@"cht_checked") forState:UIControlStateSelected];
    readBtn.userInteractionEnabled = NO;
    [contentView addSubview:readBtn];
    
    
    UIButton *completeBtn = [UIButton creatWithFrame:CGRectMake(autoScaleW(30), readBtn.bottom + 10, (contentView.width - autoScaleW(60)-10)/2.f, 35)
                                                font:[UIFont systemFontOfSize:15]
                                                text:completeTitle
                                              action:@selector(countDownBoxComplete)
                                              target:self];
    completeBtn.backgroundColor = [UIColor lightGrayColor];
    completeBtn.enabled = NO;
    [contentView addSubview:completeBtn];
    
    
    UIButton *cancleBtn = [UIButton creatWithFrame:CGRectMake(completeBtn.right + 10, completeBtn.top, completeBtn.width, completeBtn.height)
                                                font:completeBtn.titleLabel.font
                                                text:cancleTitle
                                           textColor:[UIColor grayColor]
                                              action:@selector(countDownBoxDismiss)
                                              target:self];
    [cancleBtn setBorderWithColor:[UIColor grayColor] borderWidth:0.5];
    [contentView addSubview:cancleBtn];
    
    contentView.height = cancleBtn.bottom + 20;
    contentView.top = (SCREEN_HEIGHT - contentView.height)/2.f - 20;
    

    objc_setAssociatedObject(self, CountDownBoxCompleteBlock, completeBlock, OBJC_ASSOCIATION_COPY_NONATOMIC);
    objc_setAssociatedObject(self, CountDownBoxReadBtn, readBtn, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    
    
    [contentView.layer scale];
    
    [UIViewController openTimerWithLimit:30 progressBlock:^(NSString *seconds){
        
        @autoreleasepool {
            NSString *text = [NSString stringWithFormat:@"(%@s)后可进行操作",seconds];
            NSMutableAttributedString *mttStr = [[NSMutableAttributedString alloc]initWithString:text];
            [mttStr setAttributes:@{NSForegroundColorAttributeName:[UIColor darkGrayColor]} range:[text rangeOfString:@"后可进行操作"]];
            timeLabel.attributedText = mttStr;
        }
        
    } completeBlock:^{
        NSMutableAttributedString *mttStr = [[NSMutableAttributedString alloc]initWithString:@"(0s)后可进行操作"];
        [mttStr setAttributes:@{NSForegroundColorAttributeName:[UIColor darkGrayColor]} range:NSMakeRange(4, 6)];
        timeLabel.attributedText = mttStr;
        completeBtn.enabled = YES;
        completeBtn.backgroundColor = kColor_AppNavColor;
        readBtn.userInteractionEnabled = YES;
    }];
    
}

- (void)countDownBoxRead:(UIButton *)btn{
    
    btn.selected = !btn.selected;
    
}

- (void)countDownBoxDismiss{
    
    //这里一定移除绑定，否则有内存泄漏
    objc_removeAssociatedObjects(self);
    UIView *bgView = [self.view viewWithTag:7890];
    [bgView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    [bgView removeFromSuperview];
    bgView = nil;
    
}

- (void)countDownBoxComplete{
    
    UIButton *readBtn = objc_getAssociatedObject(self, CountDownBoxReadBtn);
    if (!readBtn.selected) {
        
        [MBProgressHUD showError:@"请确认已阅读并同意了上述内容" toView:self.view];
        return;
    }
    
    void (^ clickBlock)() = objc_getAssociatedObject(self, CountDownBoxCompleteBlock);
    !clickBlock? :clickBlock();
    [self countDownBoxDismiss];
}

/**
 显示徽商银行弹框
 
 @param flag 状态： 0未开通，1已开通，2账户未激活，3尚未设置交易密码
 */
- (void)showHsBoxWithFlag:(NSInteger)flag{
    
    switch (flag) {
        case 0:
        {
            WeakSelf
            [self showWarnViewWithText:@"您未开通银行存管账户"
                         textAlignment:1
                           buttonTitle:@"去开通"
                                 block:^{
                                     
                YPGoWebView(String_Connect(CMD_DEPOSITORY, @"&token=", TOKEN), weakSelf.navigationController);
            }];
        }
            break;
        case 1:
        {
        
        }
            
            break;
        case 2:
        {
            WeakSelf
            [self showWarnViewWithText:@"您的银行存管账户未激活"
                         textAlignment:1
                           buttonTitle:@"去绑卡激活"
                                 block:^{
                                     
                                     YPGoWebView(String_Connect(CMD_DEPOSITORYBIND, @"&token=", TOKEN), weakSelf.navigationController);
                                 }];
        }
            
            break;
        case 3:
        {
            WeakSelf
            [self showWarnViewWithText:@"您尚未设置交易密码"
                         textAlignment:1
                           buttonTitle:@"去设置"
                                 block:^{
                                     
                                     YPGoWebView(String_Connect(CMD_SETTING_PAY_PSD, @"&token", TOKEN), weakSelf.navigationController);
                                 }];
        }
            
            break;
            
        default:
            break;
    }
}


@end
